// 异步线程池
class AsyncPool {
  constructor(parallelCount = 3) {
    this.parallelCount = parallelCount; // 并发数量
    this.tasks = [];
    this.runningCount = 0;
  }
  add(task) {
    return new Promise((resolve, reject) => {
      this.tasks.push({
        task,
        resolve,
        reject
      });
      this._run(); // 没有正在执行的任务，就立即执行任务
    });
  }
  _run() {
    while (this.runningCount < this.parallelCount && this.tasks.length > 0) {
      let { task, resolve, reject } = this.tasks.shift();
      this.runningCount++;
      task().then(resolve, reject).finally(() => {
        this.runningCount--;
        this._run(); // 这里不执行，就只能完成parallelCount个任务
      });
    }
  }
}

export default AsyncPool;